package com.csgc.camera.widget.dialog.adapter

import android.content.Context
import android.content.pm.ActivityInfo
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView.Adapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.csgc.camera.bean.MaskEditInfo
import com.csgc.camera.biz.other.activity.MaskDateStyleActivity
import com.csgc.camera.biz.other.activity.UpdateMaskInfoContentActivity
import com.csgc.camera.constants.MaskConfig
import com.csgc.camera.events.ChangeRemarkStatus
import com.csgc.camera.events.JumpToLocationEvent
import com.csgc.camera.events.MaskContentStateEvent
import com.csgc.camera.events.MaskEditDateEvent
import com.csgc.camera.events.MaskUpdateContent
import com.csgc.camera.storage.MaskPreference
import com.csgc.camera.util.TimeUtil
import com.csgc.camera.util.clickWithTrigger
import com.csgc.camera.widget.CoilEngine
import com.csgc.camera.widget.dialog.DatePickerDialog
import com.cysd.spsyxj.databinding.ItemMaskEditBinding
import com.drake.channel.sendEvent
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.language.LanguageConfig

class MaskEditInfoAdapter(val context: Context,val list:ArrayList<MaskEditInfo> = ArrayList()):Adapter<MaskEditInfoAdapter.MaskEditInfoHolder>() {

    var maskListener:OnMaskItemListener?=null
    private val timeDialog:DatePickerDialog by lazy {
       val dialog =  DatePickerDialog(context)
        dialog.pickListener = object :DatePickerDialog.OnPickListener{
            override fun onSelected(year: Int, month: Int, day: Int, hour: Int, min: Int) {
                MaskConfig.maskEditDate = TimeUtil.changeTime(year, month, day,hour,min)
                sendEvent(MaskEditDateEvent(MaskConfig.maskEditDate))
            }
        }
        dialog
    }
    fun update(data:List<MaskEditInfo>,customList:List<MaskEditInfo>?=null){
        list.clear()
        list.addAll(data)
        if (!customList.isNullOrEmpty()){
            list.addAll(customList)
        }

       val iterator =  list.iterator()
        while (iterator.hasNext()){
            val info = iterator.next()
            if (!info.needShow){
                iterator.remove()
            }
        }

        notifyDataSetChanged()
    }


    fun add(item:MaskEditInfo){
        list.add(item)
        notifyItemInserted(list.size-1)
    }

    private val clickableList:List<String> by lazy {
        listOf("备注","品牌名称","品牌宣传语/口号","汽车品牌" ,"保养项目","车间技师" ,"车牌","巡检类型","巡检人",
            "问题备注","维修人","维修内容","物业单位","配送员","外卖员","留样人",
            "拍摄人","拍摄地点","巡查内容","工程名称","故障原因","维修建议",
        "负责任人","清洁内容","清洁区域","施工区域","施工内容","责任人","施工单位","环卫人员","单位名称","服务单位","服务内容","负责人")

    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MaskEditInfoHolder {
        return MaskEditInfoHolder(ItemMaskEditBinding.inflate(LayoutInflater.from(context),parent,false))
    }

    override fun onBindViewHolder(holder: MaskEditInfoHolder, position: Int) {
        val data = list[position]
        holder.binding.apply {

            tvTitle.text = data.title
            tvContent.text = data.content
            if (data.canHide){
                switchItem.visibility = View.VISIBLE
            }else{
                switchItem.visibility = View.GONE
            }

//            switchItem.setOnCheckedChangeListener { compoundButton, b ->
//                if (data.title == "备注" && !data.isCustom){
//                    sendEvent(ChangeRemarkStatus(b))
//                }else if (data.title == "地点" && !data.isCustom){
//                    sendEvent(MaskContentStateEvent(b, title = data.title, isCustom = false))
//                }
//
//                data.isOpen = b
//                maskListener?.onStatusChange(position,b,data.isCustom)
//            }

            switchItem.setOnClickListener {
                val b = !switchItem.isSelected
                if (data.title == "备注" && !data.isCustom){
                    sendEvent(ChangeRemarkStatus(b))
                }else if (data.title == "地点" && !data.isCustom){
                    sendEvent(MaskContentStateEvent(b, title = data.title, isCustom = false))
                }
                data.isOpen = b
                switchItem.isSelected = b
                maskListener?.onStatusChange(position,b,data.isCustom)
            }

            switchItem.isSelected = data.isOpen
//            if(data.title == "修改时间" && !data.isCustom){
//                if (UserPreference.instance.isVip()){
//                    ivVipFlag.visibility = View.INVISIBLE
//                }else{
//                    ivVipFlag.visibility = View.VISIBLE
//                }
//
//            }else{
//                ivVipFlag.visibility = View.INVISIBLE
//            }


            root.clickWithTrigger {
                if(data.title == "拍摄时间" && !data.isCustom){
                    MaskDateStyleActivity.launch(context)
                }else if(data.title == "修改时间" && !data.isCustom){
//                    if (!UserPreference.instance.isVip()){
//                        VipCenterActivity.launch(context)
//                        return@clickWithTrigger
//                    }
                    timeDialog.showDialog()
                }else if(data.title == "地点" && !data.isCustom){
                   sendEvent(JumpToLocationEvent(true))
                }else if(clickableList.contains(data.title) && !data.isCustom){
                    UpdateMaskInfoContentActivity.launch(context,data.title)
                }else if(data.title == "品牌logo" && !data.isCustom){
                    PictureSelector.create(context)
                        .openGallery(SelectMimeType.ofImage())
                        .setImageEngine(CoilEngine())
                        .setLanguage(LanguageConfig.CHINESE)
                        .setSelectionMode(SelectModeConfig.SINGLE)
                        .setImageSpanCount(3)
                        .isGif(false)
                        .isBmp(false)
                        .isWebp(false)
                        .setSkipCropMimeType()
                        .isDisplayCamera(false)
                        .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                        .forResult(object : OnResultCallbackListener<LocalMedia?> {
                            override fun onResult(result: ArrayList<LocalMedia?>) {
//                                XLog.e("=====album${result[0]?.availablePath}")
//                                XLog.e("=====album${result[0]?.realPath}")

                                val maskType = MaskPreference.instance.getMaskType()
                                val maskId = MaskPreference.instance.getMaskId()

                                MaskConfig.maskMap[maskType]?.forEach {
                                    if (it.title == data.title && !it.isCustom){
                                        it.content = "${result[0]?.availablePath}"
                                    }
                                }
                                sendEvent(MaskUpdateContent(data.title,"${result[0]?.availablePath}"))
                            }
                            override fun onCancel() {}
                        })
                }

            }


        }
    }

    override fun getItemCount(): Int {
       return list.size
    }

    inner class MaskEditInfoHolder(val binding:ItemMaskEditBinding):ViewHolder(binding.root)

    interface OnMaskItemListener{
        fun onStatusChange(position: Int,status:Boolean,isCustom:Boolean)
    }
}